import talib as tl
import SimulationTrade as ST

ST.config("2021-8-09", "2021-8-18")
ST.openEntrustInfo = True
user = ST.User(money=15000)
# stock0 = ST.Stock("603232.SH")
# stock1 = ST.Stock("603261.SH")
stopLossPrice = 0
createPrice = 0
isCross = 0
buyDays = 0
sellDays = 0
nowDays = 1

futures = ST.Futures("SC2112.INE")


while ST.nextDay():  # 执行下一日
    print("-----------------------------------------")
    print("日", futures.nowDate, futures.nowPrice)

    nowMin = 0
    while ST.nextMin():
        avg = tl.MA(futures.oldMinData.close.values[-100:].astype(float), 30)
        # 建仓---------
        if float(futures.oldMinData.close.values[-2]) > float(avg[-2]) and \
                float(futures.oldMinData.close.values[-1]) < float(avg[-1]):  # 跌破
            allBuyNum = 0.0
            for var in user.holdingFuturesList:
                if var.case == -1:
                    allBuyNum += var.num

            if allBuyNum < user.allMoney / futures.nowPrice * 0.12:
                positions = user.allMoney / futures.nowPrice * 0.03
                print(user.buy(futures, positions, futures.nowPrice, case=-1))
                stopLossPrice = futures.nowPrice * 1.02
                createPrice = futures.nowPrice

        # ---------
        if len(user.holdingFuturesList) > 0:
            avg5 = tl.MA(futures.oldMinData.close.values[-100:].astype(float), 5)
            if futures.nowPrice <= avg5[-1] * 1.002 and createPrice * 0.997:
                stopLossPrice = futures.nowPrice * 1.001

            if futures.nowPrice >= createPrice * 1.02:
                for holding in user.holdingFuturesList:
                    if holding.futures == futures:
                        print(user.sell(futures, holding.num, futures.nowPrice, case=holding.case))

        if futures.nowPrice >= stopLossPrice:

            for holding in user.holdingFuturesList:
                if holding.futures == futures:
                    print(user.sell(futures, holding.num, futures.nowPrice, case=holding.case))

        pass
    user.put()
    print("-----------------------------------------")
    print("止损价", stopLossPrice, "  建仓价", createPrice)
